package com.epam.iunna.bookshop.controller.actions;

import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.epam.iunna.bookshop.controller.application.Constants;
import com.epam.iunna.bookshop.controller.filters.AuthFilter;
import com.epam.iunna.bookshop.controller.utils.dispatch.ActionInt;
import com.epam.iunna.bookshop.model.User;
import com.epam.iunna.bookshop.model.service.BasketBean;

public class RestoreOrder implements ActionInt{

    @Override
    public String perform(HttpServletRequest request,
            HttpServletResponse response) {

        Long orderID = Long.valueOf(0);
        try{
            orderID = Long.parseLong(request.getParameter("orderID"));
            
            BasketBean basketBean = (BasketBean) request.getSession().getAttribute(BasketBean.BASKET_BEAN_SESSION_BEAN);
            if( basketBean != null ){
                //must enter not null fields before can save
                //basketBean.saveOrder();
                request.getSession().setAttribute(BasketBean.BASKET_BEAN_SESSION_BEAN,null);
            }
            
            basketBean = new BasketBean(((User)request.getSession().getAttribute( AuthFilter.USER_SESSION_KEY )).getId());
            basketBean.restoreOrderById(orderID);
            request.getSession().setAttribute(BasketBean.BASKET_BEAN_SESSION_BEAN,basketBean);
            
        }catch(NumberFormatException e){
            System.out.println("Incorrect order id " + orderID );
            e.printStackTrace();
            return Constants.FATAL_ERROR_PAGE_PATH;
        }catch(SQLException e){
            System.out.println("Db error ");
            e.printStackTrace();
            return Constants.FATAL_ERROR_PAGE_PATH;
        }
        BooksList bookListAction = new BooksList();
        return bookListAction.perform(request, response);
    }

}
